package com.fingard.dsp.bank.helpers;

import com.fingard.FGBiz;
import com.fingard.client.DspClient;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directConfig.FileSaveSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.dsp.interact.FileServerInvokerBase;
import com.fingard.dsp.interact.IFileServerInvoker;
import com.fingard.dsp.interact.UploadFileReq;
import com.fingard.dsp.interact.UploadFileResp;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;

public class DirectFileSaveHelper {

	private FileSaveSet fileSet;
	private DirectBase dBase = null;
	private DataFileHelper dFileHelper = null;
	public DirectFileSaveHelper(DirectBase p_dBase) throws Exception{
		fileSet = FGBiz.dspCenter.dspConfig.getFileSaveSet("receipt");
		dBase = p_dBase;
		dFileHelper = new DataFileHelper(dBase);
	}
	
	/**检查配置*/
	public boolean checkSet(StringBuilder p_sb){
		if("remoteHost".equals(fileSet.saveType)){
			if(StringHelper.isNullOrEmpty(fileSet.mainHostServer)){
				p_sb.append("未配置回单主DSP服务地址\r\n");
	    		return false;
	    	}
			p_sb.append("回单主DSP服务地址："+fileSet.mainHostServer+"\r\n");
		}else if("custom.fileServer".equals(fileSet.saveType)){
			if(StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.customCode)){
				p_sb.append("未配置客户代码<customCode>\r\n");
	    		return false;
			}
		}if("shareDir".equals(fileSet.saveType)){//-共享目录
			if(StringHelper.isNullOrEmpty(fileSet.shareDir)){
				p_sb.append("未配置共享目录<shareDir>\r\n");
	    		return false;
			}
		}else{
			String mainDir = fileSet.getMainDir("");
			if(StringHelper.isNullOrEmpty(mainDir)){
				p_sb.append("未配置回单文件下载保存主目录\r\n");
	    		return false;
	    	}
			p_sb.append("回单文件下载保存主目录："+mainDir+"\r\n");
		}
		
		return true;
	}
	
	private HashMap<String,HashMap<String,String>> mapSavedRecord = new HashMap<String,HashMap<String,String>>();
	private HashMap<String,String> getSavedRecordMap(Date p_date, String p_actNum, String p_fixStr) throws Exception{
		String key1 = p_actNum+"-"+Format.Date8Format.format(p_date)+p_fixStr;
		if(!mapSavedRecord.containsKey(key1)){
			//加载已经上传过的
			HashMap<String,String> mapDay = new HashMap<String,String>();
			String daySavedRdPath = dFileHelper.getBankReceiptSavedRecordFile(p_date, p_actNum, p_fixStr);
			File dataUpedFile = new File(daySavedRdPath);
			if(dataUpedFile.exists()){
				FileInputStream inputStream = null;
				BufferedReader bufferedReader = null;
				try{
					inputStream = new FileInputStream(daySavedRdPath);  
			        bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "gbk"));
			              
			        String str = null;
			        while((str = bufferedReader.readLine()) != null){
			            String[] eachkv = str.split(":");
			            if(eachkv.length>1){
			            	mapDay.put(eachkv[0], eachkv[1]);
			            }else{
			            	mapDay.put(eachkv[0], "");
			            }
			        }
				}catch(Exception e){
					throw(e);
				}finally{
					if(bufferedReader!=null){
						bufferedReader.close();
					}
					if(inputStream!=null){
						inputStream.close();
					}
				}
			}
			mapSavedRecord.put(key1, mapDay);
		}
		return mapSavedRecord.get(key1);
	}
	
    private DspClient dspClient = null;
    private IFileServerInvoker iFsInvoker = null;
	/*
	 * <!-- 配置说明
1、saveType如果是remoteHost-远程目录，配置mainHostServer；
2、saveType如果是localhost-本地目录，配置mainDir；
3、saveType如果是shareDir-共享目录，配置shareDir；
4、saveType如果是custom.fileServer-客制化文件服务器，配置uploadUrl和downloadUrl，还有上一级的customCode
 -->*/
	/**取DSPSystem.xml中的<fileSaveSet for="receipt">，判断如何保存文件
	 * @param p_ref 文件参考号，如回单的业务参考号
	 * @throws Exception */
	public HelperResp saveFile(ReqRespHeader p_header, String p_fileType, String p_srcFile, String p_ref, Date p_date, String p_act) throws Exception{
		HelperResp resp = new HelperResp();
		String fixStrSavedRd = "saved";
		HashMap<String,String> mapSavedRd = getSavedRecordMap(p_date, p_act, fixStrSavedRd);
		if(mapSavedRd.containsKey(p_ref)){
			resp.isCompleted = true;
			resp.appendMsgLn(p_ref + "文件已经上传过，不再重复上传customFileId:" + mapSavedRd.get(p_ref));
			return resp;
		}
		String[] fvs = StringHelper.splitFileNameAndExt(p_srcFile);
		String fileName = fvs[0];
		String fileExt = fvs[1];
		String fileExtAndDot;
		if(StringHelper.hasAnyChar(fileExt)){
			fileExtAndDot = "."+fileExt;
		}else{
			fileExtAndDot = "";
		}
		String nameAndExt = fileName+fileExtAndDot;
		String targetDir = "";
		String targetPath = "";
		if(FileType.receipt.equals(p_fileType)){//回单文件
			targetDir = StringHelper.getDirPathUsingSplitGiveUpLastOne(p_ref, 3);
			targetPath = targetDir + File.separator+p_ref+"_"+p_act+fileExtAndDot;
		}
		
		String customFileId = "";
		
		if("remoteHost".equals(fileSet.saveType)){//发到远程DSP
			if(dspClient == null){
				dspClient = new DspClient(fileSet.mainHostServer);
				dspClient.timeoutSec = fileSet.getReadTimeoutSec(15, resp.sbMsg);
			}
			resp.appendMsgLn("文件"+nameAndExt+"推送至远程路径"+targetPath);
			String retXml = "";
			try {
				TcpReceiver retReceiver = dspClient.syncFile(p_srcFile, FileType.receipt, p_header.bankCode,"", targetPath);
				if(retReceiver.isCompleted){
    				retXml = new String(retReceiver.recBytes, retReceiver.contentStartIndex,retReceiver.contentLength, retReceiver.charsetName);
    				XmlTextReader retXmlRd = new XmlTextReader(retXml);
    				if("0".equals(retXmlRd.getSimpleText("RespCode"))){
    					resp.isCompleted = true;
    					resp.appendMsgLn("文件"+nameAndExt+"推送成功");
    				}else{
    					resp.appendMsgLn("文件"+nameAndExt+"推送失败，响应报文："+retXml);
    				}
    			}
    			else{
    				resp.appendMsgLn("文件"+nameAndExt+"推送失败："+retReceiver.getConnMsg());
    				resp.connState = retReceiver.connState;
    				if(retReceiver.connState.equals(ConnState.FAIL)){
    					resp.appendMsgLn("连接主DSP服务"+fileSet.mainHostServer+"失败");
    				}
    			}
			} catch (Exception e) {
				resp.appendMsgLn(LogHelper.getStackTrace(e)+"\r\nretXml:"+retXml);
			}
		}else if("custom.fileServer".equals(fileSet.saveType)){//-客制化文件服务器
			String fixStrCustom = "custom.up";
			HashMap<String,String> mapCustomUped = getSavedRecordMap(p_date, p_act, fixStrCustom);
			if(mapCustomUped.containsKey(p_ref)){
				resp.isCompleted = true;
				customFileId = mapCustomUped.get(p_ref);
				resp.appendMsgLn(p_ref+"文件"+nameAndExt+"之前已经上传，customFileId："+customFileId);
			}else{
				if(iFsInvoker==null){
					try {
	                    String className = "com.fingard.dsp.interact.custom." + FGBiz.dspCenter.dspSet.customCode.toLowerCase() + "." + "FileServerInvoker";
	                    Class<?> fsClass = Class.forName(className);
	                    if (fsClass != null) {
	                    	FileServerInvokerBase fsClassBase = (FileServerInvokerBase) fsClass.newInstance();
	                    	fsClassBase.fsSet = this.fileSet;
	                    	resp.appendMsgLn("uploadUrl:" + fileSet.uploadUrl);
	                    	resp.appendMsgLn("downloadUrl:" + fileSet.downloadUrl);
	                    	resp.appendMsgLn("username:" + fileSet.username);
	                    	resp.appendMsgLn("systemName:" + fileSet.systemName);
	                        iFsInvoker = (IFileServerInvoker) fsClassBase;
	                    }
	                }catch (Throwable t) {
	                	resp.connState = ConnState.CLASS_NOT_FOUND;
	                	resp.appendMsgLn(LogHelper.getStackTrace(t));
	                	return resp;
	                }
				}
				UploadFileReq upReq = new UploadFileReq();
				upReq.upFileLocalPath = p_srcFile;
				UploadFileResp upResp = iFsInvoker.uploadFile(upReq);
				if(upResp.isCompleted){
					resp.isCompleted = true;
					resp.appendMsgLn("文件"+nameAndExt+"上传成功，rtnFileId："+upResp.rtnFileId);
					customFileId = upResp.rtnFileId;
					
					String dayCustomUpPath = dFileHelper.getBankReceiptSavedRecordFile(p_date, p_act, fixStrCustom);
					FileHelper.appendFile(dayCustomUpPath, p_ref+":"+customFileId+"\r\n", "gbk");
					mapCustomUped.put(p_ref,customFileId);
					
				}else{
					resp.connState = upResp.connState;
					resp.sbMsg.append(upResp.sbMsg.toString());
				}
			}
		}else{//保存到本地目录或共享目录
			try{
				String tmpSaveToDir;
				if("shareDir".equals(fileSet.saveType)){//-共享目录
					tmpSaveToDir = fileSet.shareDir + File.separator + targetDir;
				}else{
					String mainDir = fileSet.getMainDir("");
					tmpSaveToDir = mainDir + File.separator + targetDir;
				}
	            File copyToDir = new File(tmpSaveToDir);
	            if (!copyToDir.exists()) {
	                copyToDir.mkdirs();
	            }
	            //targetPath = targetDir + File.separator+p_ref+"_"+p_act+fileExtAndDot;
	            String toFilePath = tmpSaveToDir + File.separator + p_ref+"_"+p_act + fileExtAndDot;
	            File eachToFile = new File(toFilePath);
	            if (!eachToFile.exists()) {
	                eachToFile.createNewFile();
	            }
	            File srcFile = new File(p_srcFile);
	            FileHelper.copyFile(srcFile, eachToFile);
	            resp.sbMsg.append("复制文件" + p_srcFile + "至" + toFilePath+"\r\n");
	            resp.isCompleted = true;
			}catch(Exception ex){
				resp.appendMsgLn(LogHelper.getStackTrace(ex));
			}
		}
		
		if(resp.isCompleted && FileType.receipt.equals(p_fileType)){//回单文件
			resp.isCompleted = false;
			resp.sbMsg.append("保存回单数据");
			String dataMapFile = targetDir+File.separator+"mapping"+"_"+p_act+".txt";
			String receiptFileName = StringHelper.getFileName(p_srcFile);
			//+ p_ref + fileExtAndDot;
			String fileContent = "<item fileName=\""+p_ref+"_"+p_act+fileExtAndDot+"\" customFileId=\""+customFileId+"\" ref=\""+p_ref+"\" srcFileName=\""+receiptFileName+"\" />\r\n";
			if(StringHelper.hasAnyChar(fileSet.mainHostServer)){
				if(dspClient == null){
					dspClient = new DspClient(fileSet.mainHostServer);
					dspClient.timeoutSec = fileSet.getReadTimeoutSec(15, resp.sbMsg);
				}
				String retXml = "";
				try {
					TcpReceiver retReceiver = dspClient.putFile(fileContent, FileType.receipt, dataMapFile, true);
					if(retReceiver.isCompleted){
	    				retXml = new String(retReceiver.recBytes, retReceiver.contentStartIndex,retReceiver.contentLength, retReceiver.charsetName);
	    				XmlTextReader retXmlRd = new XmlTextReader(retXml);
	    				if("0".equals(retXmlRd.getSimpleText("RespCode"))){
	    					resp.isCompleted = true;
	    					resp.appendMsgLn("映射信息"+fileContent+"推送成功");
	    				}else{
	    					resp.appendMsgLn("映射信息"+fileContent+"推送失败，响应报文："+retXml);
	    				}
	    			}
	    			else{
	    				resp.appendMsgLn("映射信息"+fileContent+"推送失败："+retReceiver.getConnMsg());
	    				resp.connState = retReceiver.connState;
	    				if(retReceiver.connState.equals(ConnState.FAIL)){
	    					resp.appendMsgLn("连接主DSP服务"+fileSet.mainHostServer+"失败");
	    				}
	    			}
				} catch (Exception e) {
					resp.appendMsgLn(LogHelper.getStackTrace(e)+"\r\nretXml:"+retXml);
				}	
			}else{//存本地
				String mainDir = fileSet.getMainDir("");
				String tmpSaveToDir = mainDir + File.separator + targetDir;
				dataMapFile = tmpSaveToDir+File.separator+"mapping"+"_"+p_act+".txt";
	            File toMkDir = new File(tmpSaveToDir);
	            if (!toMkDir.exists()) {
	            	toMkDir.mkdirs();
	            }
	            try {
					FileHelper.appendFile(dataMapFile, fileContent, "gbk");
					resp.isCompleted = true;
				} catch (Exception e) {
					resp.appendMsgLn(LogHelper.getStackTrace(e));
				}
			}
		}else{
			resp.sbMsg.append("非回单文件");
		}
		if(resp.isCompleted){
			String daySavedRdPath = dFileHelper.getBankReceiptSavedRecordFile(p_date, p_act, fixStrSavedRd);
			FileHelper.appendFile(daySavedRdPath, p_ref+":"+customFileId+"\r\n", "gbk");
			mapSavedRd.put(p_ref,customFileId);
		}
		return resp;
	}
}
